<?php

namespace utils;

use think\File;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls as WriterXls;
use PhpOffice\PhpSpreadsheet\Reader\Xls as ReaderXls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as ReaderXlsx;

class Excel
{
    /**
     * @param array $dataItems
     * @param array $columnNames
     * @param string $title
     * @param bool $hasRowNum 是否显示行号
     * @throws
     */
    public static function export(array $dataItems = [], array $columnNames = [], $title = '', $hasRowNum = false)
    {
        //  输出到浏览器
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 开始行
        $startRow = 1;

        // 开始列
        $dataStartCol = 65;

        $sheet->setTitle($title?$title : 'Sheet1');

        // 如果存在标题，则开始行加一
        if ($title ) {
            $sheet->setMergeCells(["A1:" . chr(64 + count($columnNames) + ($title ? 1 : 0)) . "1"])->setCellValue(chr($dataStartCol) . $startRow, $title);
            $startRow++;
        }

        // 设置列表头内容
        $i = 0;
        foreach ($columnNames as $columnName) {
            if ($hasRowNum) {
                $i++;
                $sheet->setCellValue(chr($dataStartCol) . $startRow, '编号');
            }
            $sheet->setCellValue(chr($dataStartCol + $i) . $startRow, "{$columnName}");
            $i++;
        }

        count($columnNames) && $startRow++;
        $num = 0;

        // 输出数据
        foreach ($dataItems as $dataItem) {
            $i = 0;
            if ($hasRowNum) {
                $i++;
                $sheet->setCellValue(chr($dataStartCol) . $startRow, ++$num);
            }
            foreach ($dataItem as $item) {
                $sheet->setCellValue(chr($dataStartCol + $i) . $startRow, $item);
                $i++;
            }
            $startRow++;
        }

        $writer = new WriterXls($spreadsheet);
        $writer->save('./world.xls');
    }

    public function import(File $file = null)
    {
        return $ata = [];
    }
}